package a02;

import java.awt.Color;
import java.rmi.RemoteException;
import java.util.List;
import util.Pair;

public class VierControl extends RegularControl<Byte> implements Constants {

    private static final long serialVersionUID = 1L;
    private Vier session;

    public VierControl() {
	this(new Vier(), true);
    }

    public VierControl(boolean visible) {
	this(new Vier(), visible);
    }

    public VierControl(Vier vier, boolean visible) {
	this(vier, 0, visible);
    }

    public VierControl(Vier game, int kiLevel, boolean visible) {
	super(game, new VierBoard<Byte>(game), "Vier Gewinnt", kiLevel, visible);
	this.setSession(game);
	super.getBoard()
		.setPlayerColors(Color.YELLOW, "GELB", Color.RED, "ROT");
	super.getBoard().setTableColor(Color.BLUE);
	super.getBoard().setShowBlanksActive(true);
	super.getBoard().setControl(this);
	refresh();
    }

    @Override
    public Vier getNewGame() {
	return new Vier();
    }

    @Override
    public void executeChanges(byte c, byte r, boolean remoteMove)
	    throws RemoteException {

	if (this.getBoard().getGame().getAtPosition(c, r) != this.getBoard()
		.getGame().getPlayerNone()
		|| (this.getServer() != null && this.getServer().getPlayerID() != this
			.getPlayerID())) {
	    if (this.getBoard().getGame().getAtPosition(c, r) != this
		    .getBoard().getGame().getPlayerNone())
		playSound(Sound.FAIL);
	    return;
	}
	if (this.getBoard().getGame().getAtPosition(c, r) != this.getBoard()
		.getGame().getPlayerNone()) {
	    playSound(Sound.FAIL);
	    return;
	} else {
	    playSound(Sound.CLICK);
	    Vier newState = (Vier) this.getBoard().getGame()
		    .setAtPosition(c, r);
	    this.getStack().push(this.getBoard().getGame());
	    this.getBoard().setGame(newState);
	    this.setSession(newState);
	    if (!(getServer() == null) && !remoteMove)
		this.getServer().setMouseClick(c, r, getPlayerID());
	}
	refresh();
	handleWin();
	if (!this.getStack().isEmpty()) {
	    this.getMenu().setButtonEnabled(true);
	}
    }

    @Override
    public List<Pair<Byte, Byte>> getWinningLine() {
	return session.getWinningLine();
    }

    public Vier getSession() {
	return this.session;
    }

    public void setSession(Vier session) {
	this.session = session;
    }

}
